package com.sky.tool.maven.plugins

import org.apache.maven.plugins.annotations.LifecyclePhase
import org.apache.maven.plugins.annotations.Mojo
import org.codehaus.plexus.util.FileUtils

@Mojo(defaultPhase = LifecyclePhase.PACKAGE, name = "make-linux-service")
public class LinuxServiceMojo extends AbstractServiceMojo {


    @Override
    public void generate() {
        getLog().info("开始生成 Windows Service 必要的文件");
        try {
            /*创建文件夹*/
            File distDir = new File(targetDir, "linux");
            if (!distDir.exists()) {
                distDir.mkdirs();
            }
            File logDir = new File(distDir, File.separator + "logs");
            FileUtils.mkdir(logDir.getPath());
            getLog().info("创建输出文件目录:" + targetDir);
            getLog().info("生成启动脚本 start.sh")
            new File(distDir, "start.sh") <<
                    """#!/bin/bash
work_path=\$(dirname \$(readlink -f \$0))
echo \${work_path}
nohup java ${vmOptions} -jar \${work_path}/${runJarName} >>/dev/null  2>&1 &
#记录进程号
echo \$! > ${appId}.pid
"""
            getLog().info("生成停止脚本 stop.sh")
            new File(distDir, "stop.sh") <<
                    """#!/bin/bash
PID=\$(cat  ${appId}.pid)
kill -9 \$PID
"""
            getLog().info("生成安装脚本 install.sh")
            FileUtils.copyURLToFile(getClass().getResource("/linux/install.sh"), new File(distDir, File.separator + "install.sh"));
            FileUtils.copyURLToFile(getClass().getResource("/linux/readme.txt"), new File(distDir, File.separator + "readme.txt"));

        } catch (Exception e) {
            getLog().error("制作Windows Service 失败：", e);
        }
    }
}
